package com.caifu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.pojo.*;
import com.caifu.service.*;
import com.caifu.util.AesMyUtil;
import com.caifu.util.DesUtil;
import com.caifu.util.ShiroUtil;
import com.caifu.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author szt
 * @since 2020-11-17
 */
@Controller
@RequestMapping("/sysRole")
public class SysRoleController extends AbstractController{

    final static Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysRoleMenuService roleMenuService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysOrganizationService orgService;
    @Autowired
    private SysLogService logService;

    /**
     * 进入角色权限列表页面
     * 192.168.1.180:9999/ATPension/sysRole/listPage
     * 2020年8月9日
     * codeBy szt
     */
    @RequestMapping("/listPage")
    //@RequiresPermissions("jiaosequanxian")
    public String listPage(){
        return "view/role/role_list";
    }

    /**
     * 获取角色列表
     * 192.168.1.180:9999/ATPension/sysRole/getRoleList?page=1&limit=5
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/getRoleList")
    @ResponseBody
    //@RequiresPermissions("jiaosequanxian")
    public JSONObject getRoleList(int page, int limit){
        JSONObject json = new JSONObject();
        try{
            Page<SysRole> pageCondition = new Page<>(page,limit);
            IPage<Map<String,Object>> rolePage = roleService.pageMaps(pageCondition, new QueryWrapper<SysRole>().eq("STATE","1").orderByAsc("SORT").orderByAsc("ID"));
            for (Map<String,Object> tmp:rolePage.getRecords()) {
                Integer id = (Integer)tmp.get("id");
                tmp.put("id", DesUtil.encrypt(id+""));
                tmp.remove("created_time");
                tmp.remove("updated_time");
                //获取用户授权数
                int count = userRoleService.getUserRoleCount(id);
                tmp.put("count",count);
            }
            json.put("code","0");
            json.put("msg","成功");
            json.put("count",rolePage.getTotal());
            json.put("data",rolePage.getRecords());
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取角色权限列表失败！");
            json.put("code","1");
            json.put("msg","失败");
            return json;
        }
    }


    /**
     * 进入角色权限添加页面
     * 192.168.1.180:9999/ATPension/sysRole/addPage
     * 2020年8月9日
     * codeBy szt
     */
    @RequestMapping("/addPage")
    //@RequiresPermissions("jiaosequanxian")
    public String addPage(Model model){
        //查询板块列表（排除平台管理）
        List<Map<String, Object>> appList = sysMenuService.listMaps(new QueryWrapper<SysMenu>().select("name","menu_no").eq("TYPE", "0").ne("menu_no",1));
        model.addAttribute("appList",appList);
        return "view/role/role_add";
    }

    /**
     * 进入角色权限修改页面
     * 192.168.1.180:9999/ATPension/user/editPage
     * 2020年8月9日
     * codeBy szt
     */
    @RequestMapping("/editPage")
    //@RequiresPermissions("jiaosequanxian")
    public String editPage(String roleNo, ModelMap map){
        //查询板块列表（排除平台管理）
        List<Map<String, Object>> appList = sysMenuService.listMaps(new QueryWrapper<SysMenu>().select("name","menu_no").eq("TYPE", "0").ne("menu_no",1));
        map.put("appList",appList);
        map.put("roleNo",roleNo);
        return "view/role/role_add";
    }

    /**
     * 进入角色权限查询页面
     * 192.168.1.180:9999/ATPension/user/editPage
     * 2020年8月9日
     * codeBy szt
     */
    @RequestMapping("/infoPage")
    //@RequiresPermissions("jiaosequanxian")
    public String infoPage(String roleNo, ModelMap map){
        //查询板块列表（排除平台管理）
        List<Map<String, Object>> appList = sysMenuService.listMaps(new QueryWrapper<SysMenu>().select("name","menu_no").eq("TYPE", "0").ne("menu_no",1));
        map.put("appList",appList);
        map.put("roleNo",roleNo);
        return "view/role/role_info";
    }

    /*
     * 功能描述: 获取权限列表
     * 192.168.1.180:9999/ATPension/sysRole/getMenuList?menuNo=19
     * @Author: szt
     * @Date:   2020/11/18
     */
    @RequestMapping("/getMenuList")
    @ResponseBody
    //@RequiresPermissions("jiaosequanxian")
    public JSONObject getMenuList(int menuNo){
        JSONObject json = new JSONObject();
        try{
            List<Map<String, Object>> menuList = sysMenuService.listMaps(new QueryWrapper<SysMenu>().select("name","menu_no").eq("parent_no", menuNo).orderByAsc("sort").eq("status","1"));
            menuList.forEach(menuObj->{
                List<Map<String,Object>> funcList = sysMenuService.listMaps(new QueryWrapper<SysMenu>().select("name","menu_no").eq("parent_no", menuObj.get("menu_no")).eq("status","1"));
                menuObj.put("funcList",funcList);
                menuObj.put("funcCount",funcList.size());
                funcList.forEach(funcObj->{
                    List<Map<String,Object>> btnList = sysMenuService.listMaps(new QueryWrapper<SysMenu>().select("name","menu_no").eq("parent_no", funcObj.get("menu_no")).eq("status","1"));
                    funcObj.put("btnList",btnList);
                    funcObj.put("btnCount",btnList.size());
                });
            });
            json.put("code","0");
            json.put("data",JSONArray.fromObject(menuList));
            json.put("msg","成功");
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取角色权限列表失败！");
            json.put("code","1");
            json.put("msg","失败");
            return json;
        }
    }

    /**
     * 新增修改角色
     * 2020年11月18日
     * codeBy szt
     */
    @RequestMapping("/save")
    @ResponseBody
   // @RequiresPermissions("jiaosequanxian")
    public synchronized Result save(String roleNo, String roleName, String roleDesc, String menuArr){
        try {
            roleNo = DesUtil.decrypt(roleNo);
            Result slt = roleService.save(getUserNo(), roleNo, roleName, roleDesc, menuArr);
            logService.save((SysLog) slt.getData());
            return slt;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("角色保存失败！");
            return ResultUtil.error(199,"角色保存失败！");
        }
    }

    /**
     * 获取角色信息
     * 192.168.1.180:9999/ATPension/sysRole/getRoleInfo?roleId=D15A8E25B4249FDC
     * 2020年11月19日
     * codeBy szt
     */
    @RequestMapping("/getRoleInfo")
    @ResponseBody
    //@RequiresPermissions("jiaosequanxian")
    public Result getRoleInfo(String roleId){
        try{
            //获取角色信息
            Map<String,Object> roleMap = roleService.getMap(new QueryWrapper<SysRole>().eq("id", DesUtil.decrypt(roleId)));
            //获取服务中心角色权限
            List<SysRoleMenu> fuwuList = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id",DesUtil.decrypt(roleId)).eq("app_menu_id","19"));
            String fuwuCat = "";
            for (SysRoleMenu sysRoleMenu : fuwuList) {
                fuwuCat+=sysRoleMenu.getMenuId()+"|";
            }
            //获取养老机构角色权限
            List<SysRoleMenu> yanglaoList = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id",DesUtil.decrypt(roleId)).eq("app_menu_id","59"));
            String yanglaoCat = "";
            for (SysRoleMenu sysRoleMenu : yanglaoList) {
                yanglaoCat+=sysRoleMenu.getMenuId()+"|";
            }
            //获取数据看板权限
            List<SysRoleMenu> shujuList = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id",DesUtil.decrypt(roleId)).eq("app_menu_id","89"));
            String shujuCat = "";
            for (SysRoleMenu sysRoleMenu : shujuList) {
                shujuCat+=sysRoleMenu.getMenuId()+"|";
            }

            //获取综合养老权限
            List<SysRoleMenu> zongheList = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id",DesUtil.decrypt(roleId)).eq("app_menu_id","200009"));
            String zongheCat = "";
            for (SysRoleMenu sysRoleMenu : zongheList) {
                zongheCat+=sysRoleMenu.getMenuId()+"|";
            }
            roleMap.put("fuwuCat",fuwuCat);
            roleMap.put("yanglaoCat",yanglaoCat);
            roleMap.put("shujuCat",shujuCat);
            roleMap.put("zongheCat",zongheCat);
            roleMap.put("id",roleId);

            //获取角色授权用户数量
            int count = userRoleService.getUserRoleCount(Integer.parseInt(DesUtil.decrypt(roleId)));
            roleMap.put("count",count);
            return ResultUtil.success(200, "获取角色信息成功！",roleMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取角色信息失败！");
            return ResultUtil.error(199,"获取角色信息失败！");
        }
    }

    /**
     * 删除角色
     * 2020年11月19日
     * codeBy szt
     */
    @RequestMapping("/delete")
    @ResponseBody
   // @RequiresPermissions("jiaosequanxian")
    public Result delete(String roleNo){
        SysRole oldRole = new SysRole();
        try{
            int count = userRoleService.count(new QueryWrapper<SysUserRole>().eq("role_id",DesUtil.decrypt(roleNo)));
            if(count>0){
                //已授权过用户，角色不能删除
                //日志记录  sys 组织架构模块 sys-302 角色删除
                SysLog log = new SysLog(getUserNo(), "1","sys", "sys-302", "9", getUser().getLoginName()+"删除角色失败[roleId="+oldRole.getId()+", roleName="+oldRole.getName()+"]！", new Date());
                logService.save(log);
                return ResultUtil.error(199,"此角色已授权用户，不能删除！");
            }else{
                roleNo = DesUtil.decrypt(roleNo);
                oldRole = roleService.getById(roleNo);
                oldRole.setState("9");
                roleService.updateById(oldRole);
                //日志记录  sys 组织架构模块  sys-302 角色删除
                SysLog log = new SysLog(getUserNo(), "1","sys", "sys-302", "1", getUser().getLoginName()+"删除角色成功[roleId="+oldRole.getId()+", roleName="+oldRole.getName()+"]！", new Date());
                logService.save(log);
                return ResultUtil.success(200, "删除用户成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除角色失败！");
            //日志记录  sys 组织架构模块 sys-302 角色删除
            SysLog log = new SysLog(getUserNo(), "1","sys", "sys-302", "9", getUser().getLoginName()+"删除角色失败[roleId="+oldRole.getId()+", roleName="+oldRole.getName()+"]！", new Date());
            logService.save(log);
            return ResultUtil.error(199,"删除角色失败！");
        }
    }

    /**
     * 获取角色所属用户列表
     * 192.168.1.180:9999/ATPension/sysRole/getUserList?roleId=CE69C2C9575953DB&page=1&limit=5
     * 2020年11月19日
     * codeBy szt
     */
    @RequestMapping("/getUserList")
    @ResponseBody
   // @RequiresPermissions("jiaosequanxian")
    public JSONObject getUserList(int page,int limit,String roleId){
        JSONObject json = new JSONObject();
        try{
            if(StringUtils.isNotBlank(roleId)){
                roleId=DesUtil.decrypt(roleId);
            }
            List<Map<String,Object>> userList = new ArrayList<>();
            Page<SysUserRole> pageQuery = new Page<>(page,limit);
            IPage<Map<String, Object>> userRoleList = userRoleService.pageMaps(pageQuery, new QueryWrapper<SysUserRole>().select("user_id").eq("role_id",roleId));
            for (Map<String, Object> userRole : userRoleList.getRecords()) {
                Map<String,Object> tmp = userService.getMap(new QueryWrapper<SysUser>().eq("user_no",userRole.get("user_id")));
                if(tmp!=null){
                    String tmpPhone = (String)tmp.get("PHONE");
                    tmp.put("PHONE",AesMyUtil.Decrypt(tmpPhone));
                    tmp.put("POST",Util.null2EmptyTrim((String)tmp.get("DEPT")+"/"+Util.null2EmptyTrim((String)tmp.get("POST"))));
                    Date time = (Date) tmp.get("LOGIN_TIME");
                    if(time!=null){
                        tmp.put("LOGIN_TIME",Util.dateToString(time,"yyyy-MM-dd HH:mm:ss"));
                    }
                    String status = (String) tmp.get("STATUS");
                    String statusName = ("1".equals(status)?"开通":"停用");
                    tmp.put("STATUS_NAME", statusName);
                    String orgName="";
                    String orgStr = (String) tmp.get("ORG_ID");
                    if(StringUtils.isNotBlank(orgStr)) {
                        String[] orgArr = orgStr.substring(0, orgStr.length()).split(",");
                        for (String string : orgArr) {
                            SysOrganization tmpOrg = orgService.getOne(new QueryWrapper<SysOrganization>().eq("state", "1").eq("ORG_Id", string));
                            if (tmpOrg != null) {
                                orgName = orgName + tmpOrg.getOrgName() + ",";
                            }
                        }
                        if(StringUtils.isNotBlank(orgName)) {
                            orgName=orgName.substring(0,orgName.length()-1);
                        }
                    }
                    tmp.put("ORG_NAME", orgName);
                    userList.add(tmp);
                }

            }

            json.put("code","0");
            json.put("msg","成功");
            json.put("count",userRoleList.getTotal());
            json.put("data",userList);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取角色列表失败！");
            json.put("code","1");
            json.put("msg","失败");
            return json;
        }
    }


}
